package server;
import java.net.*;
import java.util.LinkedList;
import java.io.*;

public class CMultiServer extends Thread {
	private CServer o_server;
	ServerSocket serverSocket=null;
	private boolean listening = false;
	LinkedList<CMultiServerThread> list_threads;
	public CMultiServer(CServer server){
		this.o_server = server;
		list_threads = new LinkedList<CMultiServerThread>();
	}	
	
	public void abort(){
		listening = false;
		while(!list_threads.isEmpty()){
			CMultiServerThread t = list_threads.poll();
			t.interrupt();
		}
		this.interrupt();
	}
	public void run(){
		listening = true;
        try {
            serverSocket = new ServerSocket(o_server.GetPort());
            synchronized(o_server){
            	o_server.notifyAll();
            }
        } catch (IOException e) {
            System.err.println("Could not listen on port: " + o_server.GetPort());
            System.exit(-1);
        }
        while (listening){
			try {
				CMultiServerThread t = new CMultiServerThread(serverSocket.accept(),o_server);
				list_threads.add(t);
				t.start();
			} 

        	catch (IOException e) {
				// TODO Auto-generated catch block
        		if(!this.isInterrupted()){
        			System.err.println("Could not start serverthread");
        			e.printStackTrace();
        		}
			}
        }
            try {
				serverSocket.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				System.err.println("Could not close server socket");
				e.printStackTrace();
			}
        }
	
}
